package com.cy.mall.comm.config;


import java.nio.charset.StandardCharsets;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import com.cy.mall.comm.interceptor.CustomerLoginInterceptor;

/**
 * web配置
 *
 * @author: tanyilin
 * @create: 2018年10月29日 上午10:24:04
 */
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter{

	@Value("${spring.profiles.active}")
	private String active;
	@Autowired
	private CustomerLoginInterceptor customerLoginInterceptor;
	
	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		
		if("dev".equals(active)) {
			//添加拦截器
			registry.addInterceptor(customerLoginInterceptor)
				.addPathPatterns("/customer/**");
			
			return;
		}
		
		//添加拦截器
		registry.addInterceptor(customerLoginInterceptor)
			.addPathPatterns("/customer/**");
	}
	
	/**
	 * 解决跨域问题，建议使用这种方式
	 * 
	 * @return
	 */
	@Bean
    public CorsFilter corsFilter() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        corsConfiguration.setAllowCredentials(true);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(source);
    }
	
	@Bean
	public RestTemplate restTemplate() {
		RestTemplate restTemplate = new RestTemplate();
		restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
        return restTemplate;
	}


}
